#include "CEUtilities.h"

#include "CEMeshLoadHelper.h"


MeshLoadHelper* MeshLoadHelper::g_MeshLoadHelper = NULL;


//----------------------------------------------------------------------
MeshLoadHelper* MeshLoadHelper::GetSingleton()
{
	if (!g_MeshLoadHelper)
	{
		g_MeshLoadHelper = new MeshLoadHelper();
	}

	return g_MeshLoadHelper;
}


//----------------------------------------------------------------------
Mesh* MeshLoadHelper::GetMeshLoaded(const STRING &meshFile) const
{
	map<STRING, list<Mesh*> >::const_iterator iter;

	iter = m_MeshLoaded.find(meshFile);

	if (iter != m_MeshLoaded.end())
	{
		if (iter->second.size() > 0)
		{
			return iter->second.front();
		}
	}

	return NULL;
}


//----------------------------------------------------------------------
BOOL MeshLoadHelper::TagMeshAsLoaded(const STRING &meshFile, const Mesh *mesh)
{
	map< string, list<Mesh*> >::iterator iter;
	iter = m_MeshLoaded.find(meshFile);

	if (iter != m_MeshLoaded.end())	
	{
		list<Mesh*>::const_iterator p;
		for(p = iter->second.begin(); p != iter->second.end(); ++p)
		{
			if (*p == mesh)
				break;
		}

		if (p == iter->second.end())
		{
			iter->second.push_back(const_cast<Mesh*>(mesh));
			return TRUE;
		}
	}
	else
	{
		list<Mesh*> loadedMeshList;
		loadedMeshList.push_back(const_cast<Mesh*>(mesh));
		m_MeshLoaded.insert(make_pair(meshFile, loadedMeshList));
		return TRUE;
	}

	return FALSE;
}


//----------------------------------------------------------------------
BOOL MeshLoadHelper::TagMeshAsUnloaded(const STRING &meshFile, const Mesh *mesh)
{
	map< string, list<Mesh*> >::iterator iter;
	iter = m_MeshLoaded.find(meshFile);

	if (iter != m_MeshLoaded.end())	
	{
		list<Mesh*>::iterator p;
		for (p = iter->second.begin(); p != iter->second.end(); ++p)
		{
			if (*p == mesh)
			{
				iter->second.erase(p);
				return TRUE;
			}
		}

	}

	return FALSE;
}